package com.lczyfz.wisdom.common.utils;

import java.lang.reflect.Field;

/**
 * @author Lczy-Huang
 * @version 1.0
 * @classname ReflectClassAttribute
 * @description 反射相同/不同类直接的相同属性
 * @date 2018/11/8 19:40
 **/
public class ReflectClassAttribute<T,D> {

    /*
     * @description 将jeesite两个相同类的对象进行属性反射
     * @params [left, right]
     * @param: left: 数据库中记录
     * @param: right: vue上传记录
     * @return void
     * @author Huang Bing
     * @time 2018/11/8 19:55
     */
    public int jeesiteSameEntityReflect(T left,T right) {
        Class clazz = left.getClass();
        int resultCode = 0;
        // Entity属性拷贝
        Field[] fields = clazz.getDeclaredFields();
        resultCode+=jeesiteSameEntityFieldReflect(left,right,fields);

        // DataEntity属性拷贝
        Field[] SuperFields = clazz.getSuperclass().getDeclaredFields();
        resultCode+=jeesiteSameEntityFieldReflect(left,right,SuperFields);

        // BaseEntity属性拷贝
        Field[] GrandFatherFields = clazz.getSuperclass().getSuperclass().getDeclaredFields();
        resultCode+=jeesiteSameEntityFieldReflect(left,right,GrandFatherFields);

        return resultCode;

    }

    public int jeesiteSameEntityFieldReflect(T left,T right,Field[] fields) {
        int resultCode = 0;
        try {
            for (int i = 0; i < fields.length; ++i) {
                Field tmpField = fields[i];
                tmpField.setAccessible(true);
                // Class typeClass = tmpField.getType();
                Object leftVal = tmpField.get(left);
                Object rightVal = tmpField.get(right);
                boolean judgeBoolean = (rightVal == null) && !(tmpField.getName().equals("updateDate"))
                        && !(tmpField.getName().equals("updateBy"));
                // TODO: 只允许Object，基本类型需要改造成装箱类。
                if (judgeBoolean) {
                    tmpField.set(right, leftVal);
                }
            }
        }catch (Exception ex){
            resultCode = -1;
            ex.printStackTrace();
        }finally {
            // Nothing to do...
        }
        return resultCode;
    }

    // test demo
    /*
    public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
        CloWarning cloWarning =new CloWarning();
        CloWarning cloWarning1 = new CloWarning();
        cloWarning.setApplicationSoftware("2");
        cloWarning.setId("123");
        cloWarning.setCreateBy(new User("1"));
        cloWarning.setUpdateBy(new User("1"));
       // cloWarning1.setCreateBy(new User("2"));
        //cloWarning1.setUpdateBy(new User("2"));

        ReflectClassAttribute<CloWarning,CloWarning> reflectClassAttribute = new ReflectClassAttribute<>();
        reflectClassAttribute.jeesiteSameEntityReflect(cloWarning,cloWarning1);
        System.out.println(cloWarning1.getCreateBy());
        System.out.println(cloWarning1.getUpdateBy());
        System.out.println(cloWarning1.getId());
    }
    */
}
